#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <cstring>
#include <string>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
using namespace std;

#include "protocal.h"

// ./client 127.0.0.1 8080
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cerr << "Usage: " << argv[0] << " server_ip  server_port " << endl;
        exit(1);
    }

    std::string server_ip = argv[1];
    int server_port = atoi(argv[2]);

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        cerr << "sock error!" << endl;
        exit(2);
    }

    // 建立连接
    struct sockaddr_in peer;
    memset(&peer, 0, sizeof(peer));
    peer.sin_family = AF_INET;
    peer.sin_port = htons(server_port);
    peer.sin_addr.s_addr = inet_addr(server_ip.c_str()); // 网络转主机 inet_addr

    if (connect(sock, (struct sockaddr *)&peer, sizeof(peer)) < 0)
    {
        cerr << "connect fail!" << endl;
        exit(3);
    }

    // 发送请求
    while (1)
    {
        request req;
        cout << "请输入左操作数# ";
        cin >> req.x;
        cout << "请输入右操作数# ";
        cin >> req.y;
        cout << "请输入操作符[+-*/%]# ";
        cin >> req.op;
        send(sock, &req, sizeof(req), 0);

        // 接受数据
        response res;
        recv(sock, &res, sizeof(res), 0); // 阻塞式
        cout << "status: " << res.code << endl;
        cout << req.x << req.op << req.y << " = " << res.result << endl;
    }
    return 0;
}